const {
	Controller
} = require("uni-cloud-router");
const {
	success,
	fail,
	verify_token,
	build_token,
	create_uuid,
	encrypt,
	decrypt,
	isFieldExist,
	whereObj,
	isHttpMethod,
	isAdmin,
	isSuperAdmin,
	isAuthorities,
	
} = require('mh-utils');
//静态配置
const createConfig = require('uni-config-center')
const envCfg = createConfig({
	pluginId: 'env'
}).config()

module.exports = class MenuController extends Controller {
	/**
	 * 获取指定租户的菜单数据
	 * @example ?tenantId=点击角色的tenantId
	 */
	async list(){
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'GET')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:menu:list')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try{
				var _tenant = await dbJQL.collection("mh-sys-tenant")
					.where(`_id == '${ctx.data.tenantId}'`)
					.get({
						getOne: true
					})
				
				var where = '';
				where = whereObj({where,query:`menuId in ${JSON.stringify(_tenant.data.menuIds)}`});
				where = whereObj({where,query:`deleted != 1`});
				var sort = 'sortNumber';
				var order = 'asc';
				var result = await dbJQL.collection("mh-sys-menu")
					.where(`${where}`)
					.orderBy(`${sort}`, `${order}`)
					.get()
				if(result.data){
					return success({
						code: 0,
						data: result.data
					})
				}
				return fail({
					code: 1,
				})
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 分页查询
	 */
	async page() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'GET')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:menu:list')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try{
				var _tenant = await dbJQL.collection("mh-sys-tenant")
					.where(`_id == '${ctx.auth.tenantId}'`)
					.get({
						getOne: true
					})
				var where = "";
				
				// 查询条件
				var title = ctx.data.title;
				var path = ctx.data.path;
				var menuType = ctx.data.menuType;
				
				var sort = 'sortNumber';
				var order = 'asc';
				if (isFieldExist(title)) {
					where = whereObj({where,query:`${new RegExp(title,'i')}.test(title)`});
				}
				if (isFieldExist(path)) {
					where = whereObj({where,query:`${new RegExp(path,'i')}.test(path)`});
				}
				if (isFieldExist(menuType)) {
					where = whereObj({where,query:`menuType==${menuType}`});
				}
				if(!isSuperAdmin(ctx)){
					where = whereObj({where,query:`menuId in ${JSON.stringify(_tenant.data.menuIds)}`});
				}else{
					where = whereObj({where,query:`tenantId=="0"`});
				}		
				where = whereObj({where,query:`deleted != 1`});
				
				// 分页
				var page = ctx.data.page || 1;
				var limit = ctx.data.limit || 500;
				var result = await dbJQL.collection("mh-sys-menu")
					.where(`${where}`)
					.orderBy(`${sort}`, `${order}`)
					.skip((page*1 - 1) * limit)
					.limit(limit*1)
					.get({
						getCount: true
					})
				if(!result.data){
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
				return success({
					code: 0,
					data: {
						list: result.data,
						count: result.count,
					}
				})
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 新增
	 * @example data
	 */
	async add() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'POST')){
			if(!isSuperAdmin(ctx)){
				return fail({
					code: 1,
					message: '非Super管理员无权限'
				})
			}
			try{
				delete ctx.data._id;
				var result = await dbJQL.collection("mh-sys-menu")
					.add({
						...ctx.data,
						"createUserId": ctx.auth.loginUserId,
						"tenantId": ctx.auth.tenantId,
					})
				if(result.id) {
					await dbJQL.collection("mh-sys-menu")
						.doc(`${result.id}`)
						.update({
							menuId: result.id,
						})
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 修改
	 * @example data
	 */
	async update() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'PUT')){
			if(!isSuperAdmin(ctx)){
				return fail({
					code: 1,
					message: '非Super管理员无权限'
				})
			}
			try{
				var menuId = ctx.data._id;
				if(!menuId) return fail({
					code: 1,
					message: '参数无效'
				})
				delete ctx.data._id; //_id带到查询数据库会报错
				delete ctx.data.tenantId;
				var result = await dbJQL.collection("mh-sys-menu")
					.doc(menuId)
					.update({
						...ctx.data,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 删除
	 * @example ?_id=111111&createUserId=2222222
	 */
	async remove() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'DELETE')){
			if(!isSuperAdmin(ctx)){
				return fail({
					code: 1,
					message: '不可删除，请联系管理员'
				})
			}
			
			try{
				var menuId = ctx.query._id;
				if(!menuId) return fail({
					code: 1,
					message: '参数无效'
				})
				//删除
				var result = await dbJQL.collection("mh-sys-menu")
					.doc(menuId)
					.update({
						deleted: 1,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	
	
	
	
	
}

